JSEventStreamInterceptor = """
(() => {
    // 确保全局存储对象存在
    window.EventStreamTraces = window.EventStreamTraces || {};
    
    // 查找响应头中的 trace ID
    function findTraceId(headers) {
        for (const key in headers) {
            if (key.toLowerCase().includes('trace')) {
                return headers[key];
            }
        }
        return null;
    }
    
    // 处理事件流数据
    function processEventStream(traceId, text) {
        if (!traceId) return;
        
        // 确保该 traceId 的数组存在
        window.EventStreamTraces[traceId] = window.EventStreamTraces[traceId] || [];
        
        // 解析事件流数据
        const events = text.split('\\n\\n').filter(chunk => chunk.trim() !== '');
        
        for (const event of events) {
            const lines = event.split('\\n');
            const eventData = {};
            
            for (const line of lines) {
                if (line.startsWith('data:')) {
                    eventData.data = line.slice(5).trim();
                } else if (line.startsWith('event:')) {
                    eventData.event = line.slice(6).trim();
                } else if (line.startsWith('id:')) {
                    eventData.id = line.slice(3).trim();
                }
            }
            
            if (Object.keys(eventData).length > 0) {
                window.EventStreamTraces[traceId].push(eventData);
            }
        }
        
        var event_stream_ready = document.querySelector('#event_stream_ready') 
        
        if (!event_stream_ready) {
            event_stream_ready = document.createElement('div')
            event_stream_ready.id = 'event_stream_ready'
            event_stream_ready.style.opacity = '0'
            document.body.appendChild(event_stream_ready)
        }
        
        var trace_el = document.querySelector(`#event_stream_ready #trace_id_${traceId}`)
        
        if (!trace_el) {
            trace_el = document.createElement('div')
            trace_el.id = `trace_id_${traceId}`
            event_stream_ready.appendChild(trace_el)
        }
        
        trace_el.innerHTML = JSON.stringify(window.EventStreamTraces[traceId])
    }
    
    // 拦截 fetch
    const originalFetch = window.fetch;
    window.fetch = async function(...args) {
        const response = await originalFetch.apply(this, args);
        
        // 创建响应的克隆，因为响应体只能被消费一次
        const responseClone = response.clone();
        
        // 检查是否为事件流
        const contentType = responseClone.headers.get('content-type') || '';
        if (contentType.includes('text/event-stream')) {
            // 获取 trace ID
            const traceId = findTraceId(Object.fromEntries([...responseClone.headers.entries()]));
            
            // 读取和处理响应流
            const reader = responseClone.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';
            
            reader.read().then(function processStream({ done, value }) {
                if (done) {
                    // 处理最后的缓冲区
                    if (buffer) {
                        processEventStream(traceId, buffer);
                    }
                    return;
                }
                
                // 解码并添加到缓冲区
                buffer += decoder.decode(value, { stream: true });
                
                // 处理完整的事件
                const completeEvents = buffer.split('\\n\\n');
                
                // 保留最后一个可能不完整的事件
                if (completeEvents.length > 1) {
                    const lastEvent = completeEvents.pop();
                    processEventStream(traceId, completeEvents.join('\\n\\n') + '\\n\\n');
                    buffer = lastEvent;
                }
                
                // 继续读取流
                return reader.read().then(processStream);
            }).catch(error => {
                console.error('Error processing event stream:', error);
            });
        }
        
        return response;
    };
    
    // 拦截 XMLHttpRequest
    const originalXHROpen = XMLHttpRequest.prototype.open;
    const originalXHRSend = XMLHttpRequest.prototype.send;
    
    XMLHttpRequest.prototype.open = function(...args) {
        this._xhrArgs = args;
        return originalXHROpen.apply(this, args);
    };
    
    XMLHttpRequest.prototype.send = function(...args) {
        const xhr = this;
        const originalOnReadyStateChange = xhr.onreadystatechange;
        let lastProcessedLength = 0;
        
        xhr.onreadystatechange = function() {
            // 对事件流响应进行处理：在状态为 LOADING(3) 或 DONE(4) 时处理新接收的数据
            if ((xhr.readyState === 3 || xhr.readyState === 4) && xhr.responseText) {
                const contentType = xhr.getResponseHeader('content-type') || '';
                if (contentType.includes('text/event-stream')) {
                    // 只处理新到达的数据
                    if (xhr.responseText.length > lastProcessedLength) {
                        // 获取所有响应头
                        const headers = {};
                        const headerLines = xhr.getAllResponseHeaders().split('\\r\\n');
                        for (const line of headerLines) {
                            if (line) {
                                const parts = line.split(': ');
                                const header = parts.shift();
                                const value = parts.join(': ');
                                headers[header] = value;
                            }
                        }
                        
                        // 获取 trace ID
                        const traceId = findTraceId(headers);
                        
                        // 只处理新增的部分数据
                        const newData = xhr.responseText.substring(lastProcessedLength);
                        lastProcessedLength = xhr.responseText.length;
                        
                        // 处理新接收的事件流数据
                        if (traceId && newData) {
                            processEventStream(traceId, newData);
                        }
                    }
                }
            }
            
            if (originalOnReadyStateChange) {
                originalOnReadyStateChange.apply(xhr);
            }
        };
        
        return originalXHRSend.apply(this, args);
    };
})();
"""